package com.rsxy.service.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiniu.util.Md5;
import com.rsxy.service.pojo.RsProduct;
import com.rsxy.service.pojo.RsWxInfo;
import com.rsxy.service.service.WxInfoService;
import com.rsxy.service.tools.MD5Util;
import com.rsxy.service.tools.RedisUtil;
import com.rsxy.service.tools.ResultUtil;
import com.rsxy.service.tools.WechatUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.security.provider.MD5;

import javax.annotation.Resource;
import java.util.*;

@Controller
@RequestMapping("/wx")
@ResponseBody
@Log4j2
@Api(tags= "用户相关接口")
public class WxLoginController {
    @Resource
    private WxInfoService wxInfoService;
    @Autowired
    private RedisUtil redisUtil;
    @ApiOperation(value = "微信登入",notes = "测试数据")
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String wxlogin(String code){
       // log.info("code:"+code);
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
        // 3.接收微信接口服务 获取返回的参数
        //log.info("SessionKeyOpenId:>>"+SessionKeyOpenId);
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");
      //  log.info("openid:"+openid+" --- sessionKey:"+sessionKey);
        Map<String, String> map=new HashMap<>();
        map.put("openid",openid);
        map.put("sessionKey",sessionKey);
        return ResultUtil.success(200,"success",map);
    }
    @ApiOperation(value = "用户登入",notes = "测试数据")
    @PostMapping("/loginInfo")
    public String user_login(@RequestParam(value = "code", required = false) String code,
                             @RequestParam(value = "rawData", required = false) String rawData,
                             @RequestParam(value = "signature", required = false) String signature,
                             @RequestParam(value = "encrypteData", required = false) String encrypteData,
                             @RequestParam(value = "iv", required = false) String iv) {
        // 用户非敏感信息：rawData
        // 签名：signature
        JSONObject rawDataJson = JSON.parseObject(rawData);
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");

        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
        log.info("signature2 :"+signature2 );
        QueryWrapper<RsWxInfo> wxInfoWrapper=new QueryWrapper<>();
        wxInfoWrapper.eq("open_id",openid);
        RsWxInfo wxInfos = wxInfoService.getBaseMapper().selectOne(wxInfoWrapper);
        String skey = UUID.randomUUID().toString();
        JSONObject userInfo = WechatUtil.getUserInfo(encrypteData, sessionKey, iv);
        RsWxInfo user=new RsWxInfo();
        if (wxInfos==null){
            long time = new Date().getTime();
            String user_id="rs-"+Long.toString(time);
            String nickName = rawDataJson.getString("nickName");
            String avatarUrl = rawDataJson.getString("avatarUrl");
            String gender = rawDataJson.getString("gender");
            String city = rawDataJson.getString("city");
            String country = rawDataJson.getString("country");
            String province = rawDataJson.getString("province");
            user.setOpenId(openid);
            user.setSkey(skey);
            user.setUserId(user_id);
            user.setSession_key(sessionKey);
            user.setCity(city);
            user.setProvince(province);
            user.setCountry(country);
            user.setAvatarUrl(avatarUrl);
            user.setGender(Integer.parseInt(gender));
            user.setNickName(nickName);
            int res=wxInfoService.getBaseMapper().insert(user);
            log.info("res:"+res);
        }else {
            user.setSkey(skey);
            wxInfoService.getBaseMapper().update(user,null);
        }

         String token=new Date().getTime()+"";
        token=MD5Util.md5(token);
        log.info("--------生成token:"+token);
        JSONObject obj=new JSONObject();
        obj.put("skey",skey);
        obj.put("openId",openid);
        obj.put("token", token);
        obj.put("user_id",wxInfos.getUserId());
        /*Object o = redisUtil.get(wxInfos.getUserId());
         if (o!=null){
             redisUtil.setExpire(wxInfos.getUserId(),3600*30);
             redisUtil.set(o.toString(),"token",3600*30);
         }else {
             redisUtil.set(token,"token",3600*30);
             redisUtil.set(wxInfos.getUserId(),token,3600*30);
         }*/
        return ResultUtil.success(200,"登录成功",obj);
    }
    @ApiOperation(value = "获取所有用户",notes = "测试数据")
    @GetMapping("/getAll")
    public List<RsWxInfo> getAllUser(){
        List<RsWxInfo> wxInfos = wxInfoService.getBaseMapper().selectList(null);
        return wxInfos;
    }
    @ApiOperation(value = "获取所有用户(分页)",notes = "测试数据")
    @GetMapping("/getPageList")
    public IPage<RsWxInfo> getPageList(Integer page, Integer limit){

        Page<RsWxInfo> page2=new Page<>(page,limit);
        IPage<RsWxInfo> page1 = wxInfoService.getBaseMapper().selectPage(page2, null);

        return page1;

    }
}
